<!-- 申报类---制表 -->
<template>
  <div class="createForm">
    <create-form-header
      ref="formHeader"
      :initial-form-data="initialFormData"
      :is-preview="isPreview"
      :disabled="disabled"
    ></create-form-header>
    <form-tree ref="formTree" :is-preview="isPreview" :tree-data="treeData"></form-tree>
  </div>
</template>

<script>
import createFormHeader from '../../components/CreateFormHeader.vue'
import formTree from './tree.vue'
import previewViewForm from '../../writeForm/applyForm/index'
import importModal from '../../components/importModal.vue'
import confirmApproval from './components/confirmApproval.vue'
import formCenterApi from '@/api/formCenter.js'
import { extractFormDescForFieldMap, setFormDescRecursively } from '../../utils/util'
import { findNodePath } from '@/views/menuList/menus'
import { mapState } from 'vuex'
import { uuid } from 'vue-uuid'
import dataEleApi from '@/api/dataElement'
export default {
  components: { formTree, createFormHeader },
  name: 'ApplyForm',
  data() {
    return {
      uploadHeaders: { authorization: localStorage.Authorization ? `Bearer ${localStorage.Authorization}` : '' },
      uploadUrl: dataEleApi.getDataUploadUrl(),
      uploadData: { bizId: '0' },
      createForm: {
        name: '',
        menu: [],
        remark: ''
      },
      ruleValidate: {},
      quotaList: [
        { label: '单位名称', icon: 'md-home', unit: 'org' },
        { label: '时间', icon: 'md-alarm', unit: 'time' },
        { label: '联系人', icon: 'md-contacts', unit: 'contact' },
        { label: '联系电话', icon: 'md-call', unit: 'phone' },
        { label: '联系邮箱', icon: 'md-mail', unit: 'email' },
        { label: '上传附件', icon: 'ios-link', unit: 'file' },
        { label: '申报标题', icon: 'md-text', unit: 'title' }
      ],
      // 默认全选上
      selections: ['org', 'time', 'contact', 'phone', 'email', 'file', 'title'],
      baseInfoList: [],
      baseInfo: {
        tip: '',
        tipFile: []
      },
      treeData: [],
      timer: null
    }
  },
  props: {
    row: {
      type: Object,
      default: () => {}
    },
    isPreview: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapState(['menuList']),
    initialFormData() {
      return {
        name: this.row.name,
        menu: findNodePath(this.menuList, this.row.menu),
        remark: this.row.remark,
        tip: this.baseInfo.tip,
        tipFile: this.baseInfo.tipFile
      }
    }
  },
  methods: {
    importHandle() {
      new this.$pageModal(
        importModal,
        {
          props: {
            formType: this.row.type
          }
        },
        data => {
          data && this.parseFileJson(data)
        }
      )
    },

    // 解析file的json转为树结构
    parseFileJson(rows) {
      try {
        let treeData = []
        let levelNodes = [null, ...Array(5).fill(null)]
        // 用于根据层级寻找或创建节点的函数
        const findOrCreateNode = (level, parentNode, label, tip) => {
          if (!parentNode) return null
          let node = parentNode.children.find(child => child.label === label)
          if (!node) {
            node = { id: uuid.v1(), label, tip, children: [] }
            parentNode.children.push(node)
          }
          levelNodes[level] = node // 更新当前层级的节点
          return node
        }

        rows.forEach(row => {
          const [level1, level1Tip, level2, level2Tip, level3, level3Tip, level4, level4Tip, level5, level5Tip] = row
          if (level1) {
            levelNodes[1] =
              levelNodes[1] && levelNodes[1].label === level1
                ? levelNodes[1]
                : { id: uuid.v1(), label: level1, tip: level1Tip, children: [] }
            if (!treeData.some(node => node.id === levelNodes[1].id)) {
              treeData.push(levelNodes[1])
            }
          }
          if (level2) {
            levelNodes[2] = findOrCreateNode(2, levelNodes[1], level2, level2Tip)
          } else {
            levelNodes[2] = null // 重置level2节点，以确保不会错误地使用之前的节点
          }
          if (level3) {
            levelNodes[3] = findOrCreateNode(3, levelNodes[2] || levelNodes[1], level3, level3Tip)
          } else {
            levelNodes[3] = null // 重置level3节点
          }
          if (level4) {
            // 注意这里回退到level2，因为level3可能不存在
            levelNodes[4] = findOrCreateNode(4, levelNodes[3] || levelNodes[2] || levelNodes[1], level4, level4Tip)
          } else {
            levelNodes[4] = null // 重置level4节点
          }
          if (level5) {
            // 注意这里同样需要回退，因为level4或level3可能不存在
            levelNodes[5] = findOrCreateNode(
              5,
              levelNodes[4] || levelNodes[3] || levelNodes[2] || levelNodes[1],
              level5,
              level5Tip
            )
          }
        })
        // 递归设置formDesc
        treeData.forEach(node => {
          setFormDescRecursively(node)
        })
        this.treeData[0].children = treeData
        this.$nextTick(() => {
          this.$refs.formTree.selectFirstNode()
        })
      } catch (error) {
        console.log('error', error)
        this.$Message.error({
          content: '导入失败',
          duration: 2
        })
      }
    },
    saveTemp(auto) {
      const config = { baseInfo: { tip: this.$refs.formHeader.formData.tip, tipFile: this.$refs.formHeader.formData.tipFile }, treeData: this.treeData }
      const params = {
        id: this.row.id,
        name: this.row.name,
        type: this.row.type,
        year: this.row.year,
        remark: this.row.remark,
        // menu: this.createForm.menu[this.createForm.menu.length - 1],
        menu: this.row.menu,
        config: JSON.stringify(config)
      }
      formCenterApi.formSaveOrUpdate(params).then(res => {
        if (res.data.code === 200) {
          this.$Message.success({
            content: auto ? '自动暂存成功' : '暂存成功',
            duration: 2
          })
        } else {
          this.$Message.error({
            content: '暂存错误',
            duration: 2
          })
        }
      })
      this.$refs.formTree.isDirty = false
    },
    handlePreview() {
      new this.$sidelipPage(previewViewForm, {
        props: {
          row: {
            // name: this.row.name,
            treeData: this.$refs.formTree.treeData,
            baseInfo: { tip: this.$refs.formHeader.formData.tip, tipFile: this.$refs.formHeader.formData.tipFile },
            // remark: this.row.remark
          },
          isPreview: true
        }
      })
    },
    cancel() {
      this.$emit('Close')
    },
    submit() {
      const fieldMap = extractFormDescForFieldMap(this.treeData)
      console.log('fieldMap', fieldMap)
      const config = { baseInfo: { tip: this.$refs.formHeader.formData.tip, tipFile: this.$refs.formHeader.formData.tipFile }, treeData: this.treeData, fieldMap }
      const submitParams = {
        id: this.row.id,
        name: this.row.name,
        type: this.row.type,
        year: new Date().getFullYear(),
        remark: this.row.remark,
        // menu: this.createForm.menu[this.createForm.menu.length - 1],
        menu: this.row.menu,
        processId: this.row.processId,
        approverList: JSON.parse(this.row.config || '{}').approverList || [],
        isApprove: JSON.parse(this.row.config || '{}').isApprove,
        config: JSON.stringify(config)
      }
      new this.$pageModal(
        confirmApproval,
        {
          props: {
            submitParams: submitParams
          }
        },
        data => {
          data && this.$emit('Close', true)
          data &&
            this.$Message.success({
              content: '提交成功',
              duration: 2
            })
        }
      )
    },
    setPageActions() {
      const btnList = [
        {
          text: '一键导入',
          handle: this.importHandle
        },
        {
          text: '暂存',
          handle: this.saveTemp
        },
        {
          text: '预览',
          handle: this.handlePreview
        },
        {
          text: '取消',
          handle: () => {
            this.$emit('Close')
          }
        },
        {
          text: '提交',
          theme: 'primary',
          handle: this.submit
        }
      ]
      this.$emit('SetPageActions', btnList)
    },

    initializeTreeData() {
      if (!this.row.config) {
        this.treeData.push({
          id: uuid.v1(),
          label: this.row.name,
          class: 'first_node',
          tip: '',
          formDesc: [
            {
              id: uuid.v1(),
              type: 'text',
              default: this.row.name,
              layout: 16,
              labelWidth: '0',
              label: '',
              class: 'title'
            }
          ],
          children: []
        })
      } else {
        try {
          const config = JSON.parse(this.row.config)
          this.baseInfo = config.baseInfo
          if (this.row.name !== config.treeData[0].label) {
            config.treeData[0].label = this.row.name
          }
          this.treeData = config.treeData
        } catch {
          console.error('解析配置失败:')
        }
      }
    }
  },
  created() {
    console.log('row', this.row)
    console.log('config', JSON.parse(this.row.config))
    this.setPageActions()
    // 初始化树数据
    this.initializeTreeData()
    this.$nextTick(() => {
      this.$refs.formTree?.selectFirstNode()
    })
  },
  mounted() {
    // 三分钟自动暂存一次
    this.timer = setInterval(() => {
      if (this.$refs.formTree.isDirty) {
        this.saveTemp(true)
      }
    }, 1000 * 60 * 3)
  },
  beforeDestroy() {
    clearInterval(this.timer)
  }
}
</script>

<style lang="less" scoped>
/deep/ .ivu-form-item-content {
  line-height: 1.5;
}
.createForm {
  padding-left: 20px;
  padding-right: 20px;
  padding-top: 10px;
}
</style>
